package controller;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import core.*;
import model.ChoiceQuestion;
import model.Paper;

public class QuestionList extends HttpServlet {
	private static final long serialVersionUID = 8191040787467997511L;
	private static PgSQL db = PgSQL.getInstance();
	private static int limit = 20;

	public void doGet(HttpServletRequest request, HttpServletResponse response){
		int pid = Tool.intval(request.getParameter("pid"));
		
		try {
			List<ChoiceQuestion> qlist = new ArrayList<ChoiceQuestion>();
			ResultSet rs = null;
			if(pid <= 0){
				rs = db.query("SELECT * FROM qz_choicequestion ORDER BY random() LIMIT " + limit);
				while(rs.next()){
					ChoiceQuestion q = ChoiceQuestion.fromDatabase(rs);
					qlist.add(q);
				}
			}else{
				List<Integer> qpoint = new ArrayList<Integer>();
				rs = db.query("SELECT q.*,p.point FROM qz_papercontent p LEFT JOIN qz_choicequestion q ON q.qid=p.qid WHERE p.pid=" + pid + " ORDER BY random()");
				while(rs.next()){
					ChoiceQuestion q = ChoiceQuestion.fromDatabase(rs);
					qlist.add(q);
					qpoint.add(rs.getInt(6));
				}
				request.setAttribute("qpoint[]", qpoint.toArray(new Integer[0]));
			
				Paper p = null;
				rs = db.query("SELECT * FROM qz_paper WHERE pid=" + pid);
				if(rs.next()){
					p = Paper.fromDatabase(rs);
				}
				request.setAttribute("paper", p);
				
				//Record Start Time For Each Paper
				request.getSession().setAttribute("paper_start_time_" + p.getPid(), System.currentTimeMillis() / 1000);
			}
			request.setAttribute("question_list[]", qlist.toArray(new ChoiceQuestion[0]));

			View.show(request, response, "question_list");
			
		} catch (Exception e){
			e.printStackTrace();
		}
	}
}
